package com.example.friend.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.CacheConstants;
import com.example.common.core.enums.ResultCode;
import com.example.common.redis.service.RedisService;
import com.example.common.security.exception.ServiceException;
import com.example.friend.domain.question.Question;
import com.example.friend.mapper.question.QuestionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class QuestionCacheManager {

    @Autowired
    private RedisService redisService;

    @Autowired
    private QuestionMapper questionMapper;

    public Long getListSize() {
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }

    public void refreshCache() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                        .select(Question::getQuestionId)
                        .orderByDesc(Question::getCreateTime));
        if (CollectionUtil.isEmpty(questionList)) {
            return;
        }
        List<Long> questionIdList = questionList.stream().map(Question::getQuestionId).toList();
        //这块是批量插入 + 尾插保证顺序(别使用单插!!!!!!)
        redisService.rightPushAll(CacheConstants.QUESTION_LIST, questionIdList);
    }


    public Long preQuestion(Long questionId) {
        //获取当前题目下标
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST, questionId);
        if (index == 0) {
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST,index-1,Long.class);
//        //方法二 -- 数据量小的时候没问题
//        List<Long> questionList = redisService.getCacheListByRange(CacheConstants.QUESTION_LIST,0,-1,Long.class);
//        int index = questionList.indexOf(questionId);
//        if (index == 0) {
//            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
//        }
//        return questionList.get(index - 1);
    }

    public Long nextQuestion(Long questionId) {
        //获取当前题目下标
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST, questionId);
        if (index == getListSize() - 1) {
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST,index+1,Long.class);
//        List<Long> questionList = redisService.getCacheListByRange(CacheConstants.QUESTION_LIST,0,-1,Long.class);
//        int index = questionList.indexOf(questionId);
//        if (index == getListSize() - 1) {
//            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
//        }
//        return questionList.get(index + 1);
    }
}
